﻿using CPPEI.Coolzon.Common;
using CPPEI.Coolzon.Data;
using CPPEI.Coolzon.Service.Contract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.Coolzon.Server.ServiceImplement
{
     public class ReqDataEventHandler : IRequestHandler
    {
        public Data.MainServiceData.Response OnHandle(Data.MainServiceData.Request request)
        {
            //start time
            DateTime startTime = DateTime.Now;
            object objData = SerializeUtility.DeserializeFromBinary(request.Data);
            if (objData == null)
            {
                Logger.Error("ReqDataEventHandler", string.Format("用户:{0},请求的数据事件:{1},数据为空！"), request.Header.UserIdentity.ToString(), request.Header.Scenario.ToString());
                return null;
            }

            ReqDataEventData reqDataEventData = (ReqDataEventData)objData;

            RespDataEventData respDataEventData = new RespDataEventData();
            respDataEventData.DataItemId = reqDataEventData.DataItemId;
            respDataEventData.DataItemName = reqDataEventData.DataItemName;
            respDataEventData.DataItemValue = reqDataEventData.DataItemValue;
            respDataEventData.DataResultName = reqDataEventData.DataResultName;
            respDataEventData.DataSeriesId = reqDataEventData.DataSeriesId;
            respDataEventData.DataSeriesName = reqDataEventData.DataSeriesName;
            respDataEventData.DataSetName = reqDataEventData.DataSetName;
            respDataEventData.DataSourceName = reqDataEventData.DataSourceName;
            respDataEventData.EventSource = reqDataEventData.EventSource;
            respDataEventData.PartName = reqDataEventData.PartName;
            
            Data.MainServiceData.Response response = new Data.MainServiceData.Response();
            response.Data = SerializeUtility.SerializeToBinary(respDataEventData);
            long handleTicks = (DateTime.Now - startTime).Ticks;
            ResponseHeader responseHeader = new ResponseHeader();
            responseHeader.Scenario = RESPONSE_SCENARIO.CONNENT;
            responseHeader.Command = 0;//RESPONSE_COMMAND.DATAEVENT;
            responseHeader.HandleTicks = handleTicks / 1000000;//微秒转秒
            responseHeader.DataLength = response.Data.Length;
            responseHeader.SendTicks = request.Header.SendTicks / 1000000;
            responseHeader.RequestHeader = request.Header;

            response.Header = responseHeader;

            return response;
        }
    }
}
